package avicit.bdp.dds.dao.utils;

import avicit.bdp.core.constant.Constants;
import org.apache.commons.collections4.CollectionUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author admin
 * resource process definition utils
 */
public class ResourceProcessDefinitionUtils {
    /**
     * get resource process map key is resource id,value is the set of process definition
     * @param list the map key is process definition id and value is resource_ids
     * @return resource process definition map
     */
    public static Map<Integer, Set<Integer>> getResourceProcessDefinitionMap(List<Map<String, Object>> list) {
        Map<Integer, String> map = new HashMap<>();
        Map<Integer, Set<Integer>> result = new HashMap<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (Map<String, Object> tempMap : list) {

                map.put((Integer) tempMap.get("id"), (String)tempMap.get("resource_ids"));
            }
        }

        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            Integer mapKey = entry.getKey();
            String[] arr = entry.getValue().split(Constants.COMMA);
            Set<Integer> mapValues = Arrays.stream(arr).map(Integer::parseInt).collect(Collectors.toSet());
            for (Integer value : mapValues) {
                if (result.containsKey(value)) {
                    Set<Integer> set = result.get(value);
                    set.add(mapKey);
                    result.put(value, set);
                } else {
                    Set<Integer> set = new HashSet<>();
                    set.add(mapKey);
                    result.put(value, set);
                }
            }
        }
        return result;
    }
}
